package servlets.adsServlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import managers.JsonManager;
import structures.Product;
import structures.ProductList;

public class SearchProducts extends HttpServlet	{
	private static final long serialVersionUID = 1L;
	
	private static final String URLBASE = "http://localhost:8080/ISellToYouRESTWebService/searchProducts?keywords=";

	protected void doGet(HttpServletRequest request, HttpServletResponse response) {
		String keywords = request.getParameter("srch-term");
		String inputLine;
		String answer = "";
		BufferedReader reader;
		StringBuffer responseBuffer;
		ProductList list = null;
		JsonManager jsonManager = new JsonManager();
		
		
		
		String url = (URLBASE + keywords).replace(" ", "%20");
		try {
			HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection();
			httpConnection.setRequestMethod("GET");
			httpConnection.setDoOutput(true); 
			httpConnection.setDoInput(true);
			httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			
			reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
			
			responseBuffer = new StringBuffer();
			
			while ((inputLine = reader.readLine()) != null) {
				responseBuffer.append(inputLine);
			}
			reader.close();
	
			answer = responseBuffer.toString();
		} catch(Exception e) {
			answer = "";
		}
		
		list = jsonManager.toProductList(answer);
		
		request.getSession().setAttribute("advertisements", list);
		
		try {
			response.sendRedirect(request.getContextPath() + "/items.jsp");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}
